/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ro.futurefeed.service;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import ro.futurefeed.model.User;
import ro.futurefeed.repository.FeedRepository;
import ro.futurefeed.repository.UserRepository;

/**
 *
 * @author georgian
 */
@Component
public class UserServiceImpl implements UserService{
    @Autowired
    private FacebookService facebookService;
    
    @Autowired
    private UserRepository userRepository;
    
    @Override
    public User getUserWithExtendedToken(String accessToken) {
        validate(accessToken);
        com.restfb.types.User myFBUser = null;
        
        try{
            myFBUser = facebookService.getFbUser(accessToken);
        }catch(Exception e){
            throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).entity("Facebook OAuth failed").build());
        }
        
        User myFutureFeedUser = userRepository.findByFBId(myFBUser.getId());
        
        String newAccessToken = facebookService.getAccessTokenExtended(accessToken);
        if(myFutureFeedUser != null) {
            myFutureFeedUser.setAccessToken(newAccessToken);
            
            userRepository.update(myFutureFeedUser);
        } else {
            myFutureFeedUser = createFutureFeedUser(myFBUser);
            myFutureFeedUser.setAccessToken(newAccessToken);
            
            userRepository.save(myFutureFeedUser);
        }
        
        return myFutureFeedUser;
    }
    
    
    private User createFutureFeedUser(com.restfb.types.User myFBUser) {
        User myUser = new User();
        myUser.setEmail(myFBUser.getEmail());
        myUser.setFbId(myFBUser.getId());
        myUser.setFbName(myFBUser.getName());
        
        if(myFBUser.getLocation() != null) {
            myUser.setLocation(myFBUser.getLocation().getName());
        }
        
        return myUser;
    }

    private void validate(String accessToken) {
        if(accessToken == null || accessToken.trim().length() == 0){
            throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build());
        }
    }
}
